import * as React from "react";
import { inject, observer } from "mobx-react";
import { Form, Input, Button, Modal, Select, Row, Col } from 'antd';
import { WrappedFormUtils } from 'antd/lib/form/Form';
import { History, Location } from 'history';
import { HomeStore, LoginStore } from '../../../../store';
import { getByIdAsync, updateSelfUserInfo, userInfo } from '../../../../basicData/api'

const FormItem = Form.Item;
const Option = Select.Option;

interface IProps {
  history: History;
  location: Location;
  children?: AudioContextLatencyCategory;
  form: WrappedFormUtils;
  homeStore: HomeStore;
  loginStore?: LoginStore;
}

interface State {
  data: any,
  isEdit: boolean
}

//初始化state
const initialState: State = {
  data: {},
  isEdit: false
};

type IState = Readonly<typeof initialState>;

@inject("homeStore", "loginStore")
@observer
class PersonalInfo extends React.Component<IProps, IState> {
  state: IState = initialState;

  shouldComponentUpdate(nextProps:React.Props<any>) {
    return true
  }

  componentDidMount(){
    const { userId } = this.props.homeStore;
    this.props.loginStore.getAllCompany();
    if(userId){
      getByIdAsync('User', userId).then((res: any) => {
        this.setState({
          data: res.result
        })
      })
    } 
    else {
      userInfo().then((res: any) => {
        const id = res['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier']
        getByIdAsync('User', id).then((res: any) => {
          this.setState({
            data: res.result
          })
        })
      })
    } 
  }


  edit = (e: React.FormEvent<any>) => {
    e.preventDefault();
    this.setState({
      isEdit: true
    })
  }

  handleSubmit = (e: React.FormEvent<any>) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err:any, values: any) => {
      if (!err) {
        delete values.confirm;
        const value = {
          ...values,
          id: this.props.homeStore.userId
        }
        updateSelfUserInfo(value).then((res: any) => {
          if(res.success) {
            Modal.success({
              title: '修改成功',
              content: '个人资料修改成功',
            });
            this.setState({
              isEdit: false
            })
          }
        }) 
      }
    });
  }

  //验证手机号
  checkAccount(rule: string, value: string, callback: any) {
    var regex=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (value ) {
      if( regex.test(value) ){
        callback();
      }else {
        callback('手机号码格式不正确');
      }
    } else {
      callback();
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { allCompany } = this.props.loginStore;
    const { isAdmin } = this.props.homeStore;
    const { data, isEdit } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (
      <Form style={{width: 800}} onSubmit={this.handleSubmit}>
        <h2>基础信息</h2>
        {
          data && data.isActive
          ? <Row>
            <Col span={12}>
            <FormItem
              {...formItemLayout}
              label="用户编码"
            >
              {getFieldDecorator('userCode', {
                initialValue: data.userCode || '',
                rules: [{ required: true, message: '请输入用户编码!', whitespace: true }],
              })(
                <Input disabled />
              )}
            </FormItem>
            </Col>
            <Col span={12}>
            <FormItem
              {...formItemLayout}
              label="用户名称"
            >
              {getFieldDecorator('userName', {
                initialValue: data.userName || '',
                rules: [{ required: true, message: '请输入用户名!', whitespace: true }],
              })(
                <Input disabled = {!isEdit} />
              )}
            </FormItem>
            </Col>
            <Col span={12} >
              <FormItem
                {...formItemLayout}
                label="真实姓名"
              >
                {getFieldDecorator('userRealName')(
                  <Input placeholder="请输入用户真实姓名" disabled = {!isEdit} />
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label="性别"
              >
                {getFieldDecorator('gender')(
                  <Select style={{ width: '100%' }}
                    placeholder="请选择性别"
                    disabled = {!isEdit} 
                  >
                    <Option value='男' >男</Option>
                    <Option value='女' >女</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label="手机号码"
              >
                {getFieldDecorator('telNumber', {
                  initialValue: data.telNumber || '',
                  rules: [{
                    type:'string', required: false, message: '请输入手机号码!'
                  },{
                    validator: this.checkAccount,
                  }],
                })(
                  <Input
                    // addonBefore={prefixSelector}
                    disabled = {!isEdit}
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label="电子邮箱"
              >
                {getFieldDecorator('email', {
                  initialValue: data.email || '',
                  rules: [{
                    type:'string', required: false, message: '请输入邮箱!'
                  }],
                })(
                  <Input
                    // addonBefore={prefixSelector}
                    disabled = {!isEdit }
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label="地址"
              >
                {getFieldDecorator('address', {
                  initialValue: data.address || '',
                  rules: [{
                    type:'string', required: false, message: '请输入地址!'
                  }],
                })(
                  <Input
                    // addonBefore={prefixSelector}
                    disabled = {!isEdit}
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label="所属公司"
              >
                {getFieldDecorator('subordinateCompanyId', {
                  initialValue: data.subordinateCompany ? data.subordinateCompany.id : '',
                  rules: [{
                    type: 'number', required: false, message: '请选择所属公司!',
                  }],
                })(
                  <Select style={{ width: '100%' }}
                    disabled
                  >
                    {
                      allCompany && allCompany.map((item: { id: number, name: string, [propName: string]: any; }, index: any) => {
                        return <Option value={item.id} key={index}>{item.name}</Option>
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={24}>
              <FormItem>
                {
                  isEdit
                  ? <Button type="primary" htmlType="submit" style={{marginRight: 20}}>提交修改</Button>
                  : <Button onClick={this.edit} style={{marginRight: 20}}>修改资料</Button>
                }
                
                <Button onClick={() => {this.props.history.go(-1)}} style={{marginRight: 20}}>取消</Button>
                <Button onClick={() => {this.props.history.push('/home/changePwd')}}>修改密码</Button>
              </FormItem>
            </Col>
          </Row>
          : <p>用户暂未激活，请联系管理员</p>
        }
        
      </Form>
    );
  }
}

export default Form.create()(PersonalInfo)